import React from 'react';
import { inject, observer } from 'mobx-react';
import { WeaTableNew } from 'comsMobx';
import { Button, Modal } from 'antd';

let WeaTable = WeaTableNew.WeaTable;
import {
  WeaTop,
  WeaTab,
  WeaRightMenu,
  WeaErrorPage,
  WeaTools,
  WeaTag,
  WeaPopoverHrm,
  WeaLocaleProvider,
} from 'ecCom';

const confirm = Modal.confirm;
const getLabel = WeaLocaleProvider.getLabel;
import CoworkConstant from '../util/CoworkConstant';
import * as CoworkUtil from '../util/CoworkUtil';

/**
 * 主题审批 页面
 */
@inject('coworkItemApprovalStore', 'coworkMainStore')
@observer
class ItemApproval extends React.Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    this.props.coworkItemApprovalStore.doInit();
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.location.key !== nextProps.location.key) {
      this.props.coworkItemApprovalStore.doInit();
    }
  }

  componentWillUnmount() {
    // 组件卸载时一般清理一些状态
    const { coworkItemApprovalStore } = this.props;

    coworkItemApprovalStore.setShowSearchAd(false); // 隐藏搜索面板
    coworkItemApprovalStore.clearFormFields(); // 清空搜索条件
  }

  render() {
    const { coworkItemApprovalStore } = this.props;
    const {
      comsWeaTableStore,
      loading,
      form,
      conditioninfo,
      showSearchAd,
      sessionkey,
    } = coworkItemApprovalStore;
    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@bn5bco@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@ggc12z@reset`}
        type="ghost"
        onClick={this.onTabReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@qo7rgr@oncancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];
    return (
      <div className="wea-cowork-itemApproval">
        <WeaPopoverHrm
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaPopoverHrm@m4gnry`}
        />

        <WeaRightMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaRightMenu@dgfotw`}
          datas={this.getRightMenu()}
          onClick={this.onRightMenuClick}
        >
          <WeaTop
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTop@ne3vwj`}
            title={getLabel(32574, '主题审批')}
            loading={loading}
            icon={CoworkConstant.icon}
            iconBgcolor={CoworkConstant.iconBgColor}
            buttons={this.getTopButtons()}
            buttonSpace={10}
            showDropIcon={true}
            dropMenuDatas={this.getRightMenu()}
            onDropMenuClick={this.onRightMenuClick}
          >
            <WeaTab
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTab@mld0w0`}
              buttonsAd={buttonsAd}
              searchType={['base', 'advanced']}
              searchsBaseValue={
                form.isFormInit &&
                form.getFormParams() &&
                form.getFormParams().name
              }
              setShowSearchAd={this.setShowSearchAd}
              showSearchAd={showSearchAd}
              hideSearchAd={this.hideSearchAd}
              searchsAd={CoworkUtil.getSearchs(form, conditioninfo, () => {
                coworkItemApprovalStore.doTableLoading();
                coworkItemApprovalStore.setShowSearchAd(false);
              })}
              onSearch={this.onSearch}
              onSearchChange={this.onSearchChange}
            />
            <WeaTable
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaTable@3kpcrj`}
              comsWeaTableStore={comsWeaTableStore}
              loading={loading}
              sessionkey={sessionkey}
              needScroll={true}
              hasOrder={true}
              onOperatesClick={this.onOperatesClick}
              getColumns={this.getNewColumns}
            />
          </WeaTop>
        </WeaRightMenu>
      </div>
    );
  }

  setShowSearchAd = (bool) => {
    this.props.coworkItemApprovalStore.setShowSearchAd(bool);
  };
  hideSearchAd = () =>
    this.props.coworkItemApprovalStore.setShowSearchAd(false);
  onSearch = () => this.props.coworkItemApprovalStore.doTableLoading();
  onSearchChange = v =>
    this.props.coworkItemApprovalStore.appendFormFields({ name: v });

  // 右键菜单
  getRightMenu() {
    let btns = [];
    btns.push({
      key: 'search',
      icon: <i className="icon-coms-search" />,
      content: getLabel(197, '搜索'),
    });
    btns.push({
      key: 'ShowCustomColumns',
      icon: <i className="icon-coms-Custom" />,
      content: getLabel(382660, '显示定制列'),
    });
    return btns;
  }

  // 右键菜单事件绑定
  onRightMenuClick = (key) => {
    const { coworkItemApprovalStore } = this.props;
    if (key == 'search') {
      this.executeSearch();
    } else if (key == 'ShowCustomColumns') {
      const { sessionkey, comsWeaTableStore } = coworkItemApprovalStore;
      comsWeaTableStore.setColSetVisible(sessionkey, true);
      comsWeaTableStore.tableColSet(sessionkey, true);
    }
  };

  // 执行搜索方法（也可用于刷新table）
  executeSearch = () => {
    const { coworkItemApprovalStore } = this.props;
    coworkItemApprovalStore.setShowSearchAd(false);
    coworkItemApprovalStore.doTableLoading();
  };

  // 获得table选中行的主键值数组。若没选中任何一条，返回空数组
  getTableSelectedValues = () => {
    const { coworkItemApprovalStore } = this.props;
    const { comsWeaTableStore } = coworkItemApprovalStore;
    // let values = comsWeaTableStore.selectedRowKeys;
    let values = comsWeaTableStore.selectedRowKeysAllPages;
    return values;
  };

  onTabSearch = () => {
    const { coworkItemApprovalStore } = this.props;
    coworkItemApprovalStore.setShowSearchAd(false);
    coworkItemApprovalStore.doTableLoading();
  };
  onTabReset = () => {
    const { coworkItemApprovalStore } = this.props;
    coworkItemApprovalStore.clearFormFields();
  };
  onTabCancel = () => {
    const { coworkItemApprovalStore } = this.props;
    coworkItemApprovalStore.setShowSearchAd(false);
  };

  // 表格单元格转义
  onOperatesClick = (record, index, operate, flag) => {
    let coworkId = record.id;
    if (flag == 0) {
      // 批准
      this.executeButtonMethod('batchItemApproval', coworkId);
    } else if (flag == 1) {
      // 删除
      this.executeButtonMethod('batchItemApprovalDelete', coworkId);
    }
  };

  // 自定义过滤渲染
  getNewColumns = (columns) => {
    let newColumns = '';
    newColumns = columns.map((column) => {
      let newColumn = column;
      newColumn.render = (text, record) => {
        // 前端元素转义
        let valueSpan =
          record[`${newColumn.dataIndex}span`] !== undefined
            ? record[`${newColumn.dataIndex}span`]
            : record[newColumn.dataIndex];
        if (newColumn.dataIndex == 'name') {
          const str =
            record.id_strspan != undefined && JSON.parse(record.id_strspan);
          return (
            <div className="cowork-list-name">
              <a
                style={record.isnew == 1 ? { fontWeight: 600 } : null}
                onClick={() => {
                  window.open(CoworkUtil.getViewCoworkUrl(record.id));
                }}
              >
                {text}
              </a>
              {record.isTop == '1' && (
                <WeaTag
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaTag@3jnxqy`}
                >
                  Top
                </WeaTag>
              )}
              {str.length > 0 && (
                <div>
                  {str.map(v => (
                    <WeaTag
                      ecId={`${
                        (this && this.props && this.props.ecId) || ''
                      }_WeaTag@zt6t2v@${v.labelColor}`}
                      closable
                      color={v.labelColor}
                      onClose={() =>
                        this.props.coworkMainStore.deleteCoworkLabels(
                          v,
                          record.id,
                        )
                      }
                    >
                      {v.labelName}
                    </WeaTag>
                  ))}
                </div>
              )}
            </div>
          );
        }
        return (
          <div
            className="wea-url"
            dangerouslySetInnerHTML={{ __html: valueSpan }}
            title={text}
          />
        );
      };
      return newColumn;
    });
    return newColumns;
  };

  // top中的按钮
  getTopButtons() {
    let _disabled = !this.getTableSelectedValues().length;
    const buttons = [];
    buttons.push(
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@y6790a@approval`}
        type="primary"
        disabled={_disabled}
        onClick={this.batchItemApproval}
      >
        {getLabel(83212, '批量批准')}
      </Button>,
    );
    buttons.push(
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@3qw9rd@delete`}
        type="primary"
        disabled={_disabled}
        onClick={this.batchItemApprovalDelete}
      >
        {getLabel(32136, '批量删除')}
      </Button>,
    );
    return buttons;
  }

  // 页面按钮 执行方法
  batchItemApproval = () => {
    this.executeButtonMethod('batchItemApproval');
  };

  batchItemApprovalDelete = () => {
    this.executeButtonMethod('batchItemApprovalDelete');
  };

  executeButtonMethod(type, values) {
    const { coworkItemApprovalStore } = this.props;
    if (!values) {
      values = this.getTableSelectedValues();
    }
    let reloadTable = this.executeSearch;

    switch (type) {
      case 'batchItemApproval': {
        confirm({
          title: getLabel(4919, '确定批准选定的信息吗？', 'note'),
          content: '',
          onOk() {
            coworkItemApprovalStore.batchCoworkItemApprove(
              {
                coworkIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
      case 'batchItemApprovalDelete': {
        confirm({
          title: getLabel(4041, '确定删除选定的信息吗？', 'note'),
          content: '',
          onOk() {
            coworkItemApprovalStore.batchItemApprovalDelete(
              {
                coworkIds: values,
              },
              reloadTable,
            );
          },
          onCancel() {},
        });
        break;
      }
    }
  }
}

export default WeaTools.tryCatch(
  React,
  props => (
    <WeaErrorPage
      ecId={`${
        (this && this.props && this.props.ecId) || ''
      }_WeaErrorPage@kcmqdc`}
      msg={
        props.error
          ? props.error
          : getLabel(186, '对不起，该页面异常，请联系管理员！', 'error')
      }
    />
  ),
  { error: '' },
)(ItemApproval);
